<?php

namespace app\model;

use app\stateData;
use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;

class OrderOtherCertificateBusiness extends Model
{

    /**
     * 证书办理
     */

    use SoftDelete;

    protected $createTime = 'create_date';
    protected $deleteTime = 'delete_date';

    public function getIds()
    {
        return $this->column ('id');
    }
    public function chargeback()
    {
        return $this->hasOne (OrderDealChargeback::class,'certificate_code','certificate_code')
            ->bind ([
                'order_company_id',
                'chargeback_performance'=>'performance',
                'charge_back_date',
                'reason',
                'get_uid_up_logoff_file',
                'notifier_get_uid',
                'push_uidup_logoff_file',
                'notifier_push_uid',
                'b_certificate_is_conpany',
                'chargeback_create_date'=>'create_date',
                'chargeback_type'=>'type'
            ])->order('create_date DESC');
    }

    public function getStatusAttr($name): array
    {
        return [
            'id' => $name,
            'text' => stateData::$_enter_certificate[$name]
        ];
    }

    public function getGetUidAttr($name)
    {
        return [
            'id' => $name,
            'text' => (new User())->getIdNickName($name) ?: ''
        ];
    }

    public function getGetOrgAttr($name)
    {
        return [
            'id' => $name,
            'text' => (new UserOrganization())->getStructureName($name) ?: ''
        ];
    }

    public function business(): \think\model\relation\HasOne
    {
        return $this->hasOne(SystemBusiness::class, 'id', 'business_id')->bind(['business_name', 'business_name']);
    }

    public function getBusinessIdAttr($name)
    {
        return [
            'id' => $name,
            'text' => (new SystemBusiness)->getBusinessIdTitle($name) ?: ''
        ];
    }

    public function getInformationFileAttr($value)
    {
        if (empty($value)) return "";
        $arr = explode(',',$value);
        $value = '';
        foreach($arr as &$v){
            $value .= config('file.url').$v .',';
        }
        return rtrim($value,',');
    }

    public function getContractFileAttr($value)
    {
        if (empty($value)) return "";
        $arr = explode(',',$value);
        $value = '';
        foreach($arr as &$v){
            $value .= config('file.url').$v .',';
        }
        return rtrim($value,',');
    }

    public function getSaleDateAttr($name)
    {
        if (empty($name) || $name === "0000-00-00 00:00:00") return "";
        return $name;
    }

    public function getCertificateLeixingAttr($name)
    {
        return [
            'id'=>$name,
            'text'=>(new SystemCertificate)->getWhereIdCertificateModel ($name)?:''
        ];
    }

    public function getCertificateLeibieAttr($name)
    {
        return [
            'id'=>$name,
            'text'=>(new SystemCertificate)->getWhereIdCertificateModel ($name)?:''
        ];
    }

    public function getCertificateDengjiAttr($name)
    {
        return [
            'id'=>$name,
            'text'=>(new SystemCertificate)->getWhereIdCertificateModel ($name)?:''
        ];
    }

    public function getCertificateZhuanyeAttr($name)
    {
        return [
            'id'=>$name,
            'text'=>(new SystemCertificate)->getWhereIdCertificateModel ($name)?:''
        ];
    }

    //前段要求 str 转 arr
    public function getCertificateIdAttr($name)
    {
        return explode (',',$name);
    }

    public function getSfkStatusAttr($name)
    {
        return [
            'id'=>$name?:'',
            'text'=>stateData::$_sfk_status[$name]
        ];
    }
    public function getInformationFileNameAttr($name)
    {
        if (!$name) return '';
        return $name;
    }
    public function getContractFileNameAttr($name)
    {
        if (!$name) return '';
        return $name;
    }

//    public function getSalePriceAttr($name)
//    {
//        if ($name == '0.00'){
//            return '';
//        }
//        return $name;
//    }
//
//    public function getCostPriceAttr($name)
//    {
//        if ($name == '0.00'){
//            return '';
//        }
//        return $name;
//    }

    public function getSfkWcDateAttr($name)
    {
        if (!$name || $name =='0000-00-00 00:00:00') return '';
        return date ('Y-m-d',strtotime ($name));
    }

    /**
     * 附属业务批量添加
     * @param $data
     * @return int
     */
    public function allInsertData($data)
    {
        return $this->insertAll($data);
    }

    /**
     * 添加证书办理
     * @param $data
     * @return \app\model\OrderOtherCertificateBusiness|\think\Model
     */
    public function addData($data)
    {
        return self::create($data);
    }

    public function getDataIds($idArr)
    {
        $list = $this
            ->whereIn ('get_uid',$idArr)
            ->field('id')->select()->toArray();
        return array_column($list, 'id');

    }

    //查询ID范围可见数据
    public function getRandDataModel($idArr)
    {
        //排除录单中的数据
//        return $this->where ('get_uid','in',$idArr)->where('status','<>',11)->select ()->toArray ();
        return $this->where ('get_uid','in',$idArr)->where('status','<>',11)->column ('id,certificate_code,sale_date');
    }
    //管理
    public function getDataModel($page, $pageNum, $ids)
    {
        return $this->where('id', 'in', $ids)->order('create_date DESC')->select()->toArray();
    }
    public function getIdCardDataModel($ids)
    {
        return $this->where('person_id_card', 'in', $ids)->order('create_date DESC')->select()->toArray ();
    }

    public function getExcelModel($id)
    {
        return $this->whereIn('id',$id)->select()->toArray();
    }

    public function getDataCountModel($ids)
    {
        return $this->where('id', 'in', $ids)->count();
    }

    public function getThatPersonDataIds($id)
    {
        return $this->where(['get_uid' => $id])->whereOr(['submit_id' => $id])->whereOr(['responsibility_uid' => $id])->column ('id');
    }

    //个人
    public function getThatPersonDataModel($id, $ids, $page = 1)
    {
//        return $this->where(function($query)use($id){
//            $query->where(['get_uid' => $id])->whereOR(['submit_id' => $id])->whereOR(['responsibility_uid' => $id]);
//        })->where('id', 'in', $ids)
//            ->order('create_date DESC')
//            ->page($page, stateData::$_page)
//            ->select();
        $data = $this->with ('chargeback')->where('id', 'in', $ids)
            ->order('create_date DESC')
            ->select()
            ->toArray();
        //判断通知人 审批人等是否是当前用户
        $result = [];
        foreach ($data as $k => $item) {
            if ($item['get_uid']['id'] == $id || $item['responsibility_uid'] == $id   || $item['submit_id'] == $id || $item['notifier_get_uid'] == $id || $item['notifier_push_uid'] == $id){
                $result[] = $item;
            }
        }

        return array_values ($result);

    }

    public function getThatPersonDataCountModel($id,$ids)
    {
        return $this->where(function($query)use($id){
            $query->where(['get_uid' => $id])->whereOR(['responsibility_uid' => $id]);
        })->where('id', 'in', $ids)->count();
    }


    public function delDataModel($id)
    {
        return self::destroy($id);
    }

    public function editDataModel($data)
    {
        return self::update($data);
    }

    /**
     * 通过证书延伸id查询证书办理详情
     * @param $id
     * @return array|null
     */
    public function getWhereIdDataModel($id)
    {
        $data = $this->where(['id' => $id])->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return [];
    }

    public function getWhereIdDataSerModel($id)
    {
        return $this->where(['id' => $id])->select()->toArray ();
    }

    public function getWhereIdDataSelectModel($id,$cer)
    {
        return $this->where(['id' => $id,'certificate_code'=>$cer])->select()->toArray ();
    }

    /**
     * 获取订单业绩归属人
     */
    public function getOrderPerformanceUidModel($id,$certificateCode)
    {
        return $this->where (['certificate_code'=>$certificateCode,'id'=>$id])->value ('performance_uid');
    }

    /**
     * 通过证书编码查询证书详情
     * @param $cer
     * @return array|null
     */
    public function getCerDataModel($cer)
    {
        $data = $this->where(['certificate_code' => $cer])->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }

    /**
     * 通过证书编号查询某个字段
     * @param $cer
     * @param $field
     * @return mixed
     */
    public function getCerDataPersonModel($cer,$field)
    {
        return $this->where(['certificate_code' => $cer])->value($field);
    }


    /**
     * 完成订单操作
     * @param $id
     */
    public function completeOperateModel($id)
    {
        return $this->where(['id' => $id])->update(['status' => -1]);
    }

    /**
     * 修改订单状态为生产中
     * @param $id
     * @return \app\model\OrderOtherCertificateBusiness
     */
    public function saveStatusInitModel($id): OrderOtherCertificateBusiness
    {
        return $this->where(['id' => $id])->update(['status' => 0]);
    }

    /**
     * 获取证书应收款
     * @param $cer
     * @return array|null
     */
    public function getFinanceFieldFindModel($cer)
    {
        $data = $this->where(['certificate_code' => $cer])->field('certificate_code,id,sale_price as receivable,cost_price,person_name,performance_uid,certificate_id,sale_date')->findOrEmpty();

        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }


    /**
     * 修改订单状态为已退单
     * @param $cer
     * @param int $status
     * @return \app\model\OrderOtherCertificateBusiness
     */
    public function setStatusBack($cer, int $status = 2)
    {
        return $this->where(['certificate_code' => $cer])->update(['status' => $status]);
    }

    /**
     * 获取出证价 收证价
     * @return array|float|int|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSummaryModel($startDate, $endDate, $uidArr, $cerId = '')
    {
        //查询时间段内成交库的certificate_code
        //拼接whereIn条件
        $cerCode = Db::table('order_deal')->whereBetweenTime ('create_date',$startDate,$endDate)->column('certificate_code');
        $cerStr = implode ($cerCode,',');
        $performance = 0;
        if (empty($cerId)) {
            $data = $this->whereBetweenTime ('sale_date',$startDate,$endDate)
                ->whereRaw('status=1 OR status= 12 OR status = 2')
                ->field('id,performance,performance_uid')
                ->select()->toArray();
//            $data = $this->whereRaw('status=1 OR status= 12 OR status = 2')->select()->toArray ();

            //判断业绩归属人是否存在uidArr
            if (!is_array ($uidArr)){
                $uidArr = explode (',',$uidArr);
            }

            foreach ($data as $datum) {
                if (empty($datum['performance_uid'])){
                    continue;
                }
                $datumPidArr = explode (',',$datum['performance_uid']);

                $datumPidCount = count($datumPidArr);
                foreach ($uidArr as $item) {
                    if (in_array ($item, $datumPidArr)){
                        $performance += round ($datum['performance']/$datumPidCount,2);
                    }
                }
            }

        }else{
//            $data = $this->whereIn('certificate_leixing', $cerId)->whereRaw ('certificate_code in ("'.$cerStr .'") OR create_date BETWEEN "'.$startDate.'" and "'.$endDate.'"')
                $data = $this->whereBetweenTime ('sale_date',$startDate,$endDate)
                ->whereRaw('status=1 OR status= 12 OR status = 2')
                ->where (['certificate_leixing'=>$cerId])
                ->field('id,performance,performance_uid')
                ->select()->toArray();

            //判断业绩归属人是否存在uidArr
            if (!is_array ($uidArr)){
                $uidArr = explode (',',$uidArr);
            }
            foreach ($data as $datum) {
                $datumPidArr = explode (',',$datum['performance_uid']);
                $datumPidCount = count($datumPidArr);
                foreach ($uidArr as $item) {
                    if (in_array ($item, $datumPidArr)){
                        $performance += round ($datum['performance']/$datumPidCount,2);
                    }
                }
            }
        }
        return ['performance_sum'=>$performance];
    }

    /**
     * 成交总数量
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function getOrderNumModel($startDate, $endDate, $uidArr): int
    {
        //查询成交时间
        $dealModel = new OrderDeal();
        $data = $this->whereRaw(' status = 1 OR status = 12 OR status = 2')->select()->toArray ();

        //判断业绩归属人是否存在uidArr
        if (!is_array ($uidArr)){
            $uidArr = explode (',',$uidArr);
        }
        $count = 0;
        foreach ($data as $datum) {
            $datumPidArr = explode (',',$datum['performance_uid']);

            foreach ($uidArr as $item) {
                if (!in_array ($item, $datumPidArr)){
                    continue;
                }

                //查看成交时间
                $dealData = $dealModel->getOrderCompanyIdFindModel($datum['id'],$datum['certificate_code']);

//                if ($dealData){
//                    if ($dealData['create_date'] > $startDate && $dealData['create_date'] < $endDate){
//                        $count++;
//                        break;
//                    }
//                }else{
                    if (strtotime ($datum['sale_date']) > strtotime ($startDate) && strtotime ($datum['sale_date']) < strtotime ($endDate)){
                        $count++;
                        break;
                    }
//                }
            }
        }
        return $count;
    }

    /**
     * Ⅱ类业务占比
     * @return mixed
     */
    public function getErLeiBusinessModel($startDate, $endDate, $idArr)
    {
        return $this->whereRaw('status = 1 OR status = 12')
            ->whereIn('get_uid', $idArr)
            ->field('sale_price-cost_price as price,business_id')
            ->group('business_id')
            ->whereBetweenTime('sale_date', $startDate, $endDate)
            ->select()->toArray();

    }

    public function getBusinessIdCountModel($id): int
    {
        return $this->where(['business_id' => $id, 'status' => 2])->count();
    }

    /**
     * Ⅱ类业绩排行榜（滚动）
     * @param $startDate
     * @param $endDate
     * @param $cerIdArr
     * @return mixed
     */
   public function getPhbModel($startDate, $endDate, $idArr, $cerIdArr)
    {
        $orderDealChargebackModel = new OrderDealChargeback();
        $tdData = $orderDealChargebackModel->getBetDateTypeModel($startDate,$endDate);
        $data = $this->whereBetweenTime('sale_date', $startDate, $endDate)
            ->whereIn('certificate_leixing', $cerIdArr)
            ->whereRaw('status = 1 OR status = 12 OR status = 2')
            ->field('id,performance_uid,performance')
            ->select()->toArray();

        $result = [];
        /**
         * 以每个人去统计
         */
        if (!is_array ($idArr)){
            $idArr = explode (',',$idArr);
        }

        foreach ($idArr as $id) {
            //统计退单
            $tdPrice = 0;
            $yj = 0;
            if ($tdData){
                foreach ($tdData as $tdDatum) {
                    //查询订单信息
                    $daOrder = $this->where (['id'=>$tdDatum['order_company_id'],'certificate_code'=>$tdDatum['certificate_code']])->find ();
                    if ($daOrder){
                        //查看业绩归属人有几人
                        $performanceArr = explode (',', $daOrder['performance_uid']);
                        foreach ($performanceArr as $performanceArrItem) {
                            if ($performanceArrItem == $id){
                                $tdPrice += $tdDatum['performance']/count($performanceArr);
                            }
                        }
                    }
                }
            }
            //统计订单
            foreach ($data as $idDatum) {
                $idArrs = explode (',',$idDatum['performance_uid']);
                $idCount = count($idArrs);
                foreach ($idArrs as $items) {
                    if ($items == $id){
                        $yj += $idDatum['performance']/$idCount;
                    }
                }
            }

            $result[] = [
                'performance_uid'=>$id,
                'all_out_price'=>$yj + $tdPrice
            ];
        }

        return $result;
    }

    /**
     * 通过证书id查询补全资料
     * @param $cer
     * @return array|null
     */
    public function getExcelInfoModel($cer): ?array
    {
        $data = $this->where(['certificate_code' => $cer])->field('person_name,sale_price,cost_price as get_price')->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }


    /**
     * Ⅰ类业绩统计 + 排行
     */
    public function getYileiWorkCount($startDate, $endDate, $cer, $uid): array
    {

        return $this->whereBetweenTime('sale_date', $startDate, $endDate)
            ->whereRaw('(status = 1 OR status = 12 OR status = 2) AND certificate_zhuanye =' . $cer . ' AND get_uid in ('.$uid.')')
            ->field('get_uid,sum(sale_price)-sum(cost_price) as all_out_price')
            ->select()->toArray();
    }

    /**
     * 查询人才姓名
     * @param $person_name
     * @return array|null
     */
    public function getPersonNameModel($person_name): ?array
    {
        return $this->where(['person_name' => $person_name,'sfk_status'=>1])->select()->toArray();

    }

    /**
     * 业绩总表修改业绩
     * @param $param
     */
    public function editIdPerformanceModel($param)
    {
        return $this->where(['certificate_code' => $param['certificate_code']])->update(['performance' => $param['performance'],'ad_performance'=>1]);
    }

    /**
     * 查询应收款
     * @param $certificate_code
     * @return mixed
     */
    public function getCerGetPriceModel($certificate_code)
    {
       return $this->where(['certificate_code'=>$certificate_code])->value ('sale_price');
    }

    /**
     * 查询应付款
     * @param $certificate_code
     * @return mixed
     */
    public function getCerOutPriceModel($certificate_code)
    {
        return $this->where(['certificate_code'=>$certificate_code])->value ('cost_price');
    }

    /**
     * 通过身份证查询关联订单
     * @param $person_id_card
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getIdCardOrderInfoModel($person_id_card)
    {
        return $this->where (['person_id_card'=>$person_id_card])->select ()->toArray ();
    }

    /**
     * 完成订单收付款
     * @param $id
     * @return
     */
    public function completeOrderSFKModel($id)
    {
        return $this->where(['id' => $id])->update(['sfk_status' => 2,'sfk_wc_date'=>date('Y-m-d H:i:s')]);
    }

    /**
     * 完成后点击返回按钮 状态改为未完成 完成时间改为空
     * @param $id
     * @return OrderOtherCertificateBusiness
     */
    public function backCompleteOrderSFKModel($id)
    {
        return $this->where(['id' => $id])->update(['sfk_status' => 1, 'sfk_wc_date' => null]);
    }

    /**
     * 查询审核人为当前id的信息id集
     * @param $id
     * @return array
     */
    public function getResponsibilityUidDataModel($id)
    {
        return $this->where (['responsibility_uid'=>$id])->column ('id');
    }
    public function editResponsibilityUidDataModel($idArr,$id)
    {
        return $this->whereIn ('id',$idArr)->update (['responsibility_uid'=>$id]);
    }

    /**
     * 查询收证人员为当前id的信息id集
     * @param $id
     * @return array
     */
    public function getGetUidDataModel($id)
    {
        return $this->where (['get_uid'=>$id])->column ('id');
    }
    public function editGetUidDataModel($idArr,$id,$org)
    {
        return $this->whereIn ('id',$idArr)->update (['get_uid'=>$id,'get_org'=>$org]);
    }

    /**
     * 查询发起人为当前id的信息id集
     * @param $id
     * @return array
     */
    public function getSubmitUidDataModel($id)
    {
        return $this->where (['submit_id'=>$id])->column ('id');
    }
    public function editSubmitUidDataModel($idArr,$id)
    {
        return $this->whereIn ('id',$idArr)->update (['submit_id'=>$id]);
    }

    /**
     * 报表中心提成比例
     * @param $bid
     * @param $uid
     * @param $startDate
     * @param $endDate
     * @return array | string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTcblModel($bid,$uid,$startDate,$endDate)
    {
        $data = $this->where (['business_id'=>$bid,'performance_uid'=>$uid])
            ->whereBetweenTime ('sale_date',$startDate,$endDate)
            ->field('sum(performance) as all_performance')
            ->find ();

        if (!$data->isEmpty ()){
            return $data['all_performance'] ?? 0;
        }
        return 0;
    }

    /**
     * 业绩总表添加备注
     * @param $param
     */
    public function editIdLabelModel($param)
    {
        return $this->where(['id'=>$param['id'],'certificate_code'=>$param['certificate_code']])->update (['label'=>$param['label']]);
    }

    /**
     * 查询今日订单个数
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function getToDayCountFindModel():int
    {
        return  $this->whereDay('create_date')->count ();
    }

}